package Linkedlists;

public class Cycle {
    public boolean hasCycle(ListNode head){
    ListNode fast=head;
        ListNode slow=head;
        while(fast!=slow){
            fast=fast.next.next;
            slow=slow.next;
        }
        return slow==fast;
    }
    public static void main(String[] args) {
        LinkedList<Integer> list = new LinkedList<>();
        for (int i = 1; i <= 5; i++) {
            list.add(i); //add默认是尾插
        }
        // 方法1：使用foreach遍历
        for (int x : list) {
            System.out.print(x + " ");
        }
        System.out.println();

        // 方法2：使用迭代器遍历->正向遍历
        ListIterator<Integer> it = list.listIterator();
        while (it.hasNext()) {
            System.out.print(it.next() + " ");
        }
        System.out.println();

        // 方法3：使用迭代器遍历->反向遍历
        ListIterator<Integer> rit = list.listIterator(list.size());
        while (rit.hasPrevious()) {
            System.out.print(rit.previous() + " ");
        }
        System.out.println();
    }
}
